<template>
  <el-dialog v-model="dialogVisible" title="重置密码" :fullscreen="isMobile">
    <el-form
      ref="form"
      :model="formData"
      :rules="rules"
      label-width="auto"
      status-icon
    >
      <el-form-item label="旧密码" prop="oldpassword">
        <el-input
          v-model="formData.oldpassword"
          type="password"
          placeholder="请输入旧密码"
          show-password
        />
      </el-form-item>
      <el-form-item label="新密码" prop="newpassword">
        <el-input
          v-model="formData.newpassword"
          type="password"
          placeholder="请输入新密码"
          show-password
        />
      </el-form-item>
      <el-form-item label="确认新密码" prop="repassword">
        <el-input
          v-model="formData.repassword"
          type="password"
          placeholder="确认输入新密码"
          show-password
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="dialogVisible = false">取消</el-button>
      <el-button type="primary" @click="onSubmit">确定</el-button>
    </template>
  </el-dialog>
</template>
<script setup>
import { ref, reactive, computed } from "vue";
import { updatePasswordApi } from "../api";
import { useWindowSize } from "@vueuse/core";
const { width } = useWindowSize();
const isMobile = computed(() => width.value < 768);

const dialogVisible = ref(false);
const form = ref(null);

const formData = ref({
  oldpassword: "",
  newpassword: "",
  repassword: "",
});
// 表单验证规则
const rules = reactive({
  oldpassword: [
    { required: true, message: "请输入密码", trigger: "blur" },
    { min: 6, max: 16, message: "密码长度在 6 到 16 个字符", trigger: "blur" },
  ],
  newpassword: [
    { required: true, message: "请输入密码", trigger: "blur" },
    { min: 6, max: 16, message: "密码长度在 6 到 16 个字符", trigger: "blur" },
    {
      validator: (rule, value, callback) => {
        if (value == formData.value.oldpassword) {
          callback(new Error("新密码不能和旧密码相同"));
        } else {
          callback();
        }
      },
      trigger: "blur",
    },
  ],
  repassword: [
    { required: true, message: "请输入密码", trigger: "blur" },
    { min: 6, max: 16, message: "密码长度在 6 到 16 个字符", trigger: "blur" },
    {
      validator: (rule, value, callback) => {
        if (value !== formData.value.newpassword) {
          callback(new Error("两次输入的密码不一致"));
        } else {
          callback();
        }
      },
      trigger: "blur",
    },
  ],
});

const onSubmit = () => {
  form.value.validate(async (valid) => {
    if (valid) {
      try {
        await updatePasswordApi(formData.value);
        localStorage.clear("token");
        router.push("/login");
      } catch (error) {
        console.error(error);
      }

      dialogVisible.value = false;
    }
  });
};

const open = () => {
  dialogVisible.value = true;
  if (form.value) {
    form.value.resetFields();
  }
};

const close = () => {
  dialogVisible.value = false;
};

defineExpose({
  open,
  close,
});
</script>
